package cn.wenhaha.app.job.script;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.hutool.script.ScriptUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * TODO js执行类
 *
 * @author <a href="mailto:wyndem@qq.com">wynde</a>
 * @version 1.0
 * @date 2020-10-02 16:59 星期五
 */
public class JsScript implements ScriptRun {

    private  final  String PREFIX="js:";

    private final String template = "function handleJs(){ \n" +
            "var data={};\n" +
            "{} \n" +
            "}\n handleJs()";

    private final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public String prefix() {
        return PREFIX;
    }


    @Override
    public Object execute(String scriptCode, Entity entity) throws Exception {
        String  dataJson =  objectMapper.writeValueAsString(entity);
        String format = StrUtil.format(template, dataJson, scriptCode);
        return ScriptUtil.eval(format);
    }
}
